package com.hl.card.modular.packBack.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hl.card.common.constant.factory.PageFactory;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.dao.ZoneUserAwardMapper;
import com.hl.card.common.persistence.dao.ZoneUserAwardThreeMapper;
import com.hl.card.common.persistence.model.DistinguishIdCard;
import com.hl.card.common.persistence.model.ZoneUserAward;
import com.hl.card.common.persistence.model.ZoneUserAwardThree;
import com.hl.card.common.util.DateUtils;
import com.hl.card.common.util.HttpUtils;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.core.shiro.ShiroUser;
import com.hl.card.modular.packBack.model.Config;
import com.hl.card.modular.packBack.service.DistinguishService;
import com.hl.card.mq.Mq4NotifyDemo;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hl.card.mq.MqCustomConfig.QUEUE_UNFREEZE;
import static org.apache.commons.codec.binary.Base64.encodeBase64;

/**
 * 身份证审核
 * 
 * @author 袁伟
 *
 */
@RequestMapping("/distinguish")
@Controller
public class DistinguishController  extends BaseController{
	@Autowired
	private ZoneUserAwardMapper zoneUserAwardMapper;
	@Autowired
	private ZoneUserAwardThreeMapper zoneUserAwardThreeMapper;
	@Autowired
	private DistinguishService  distinguishService;
	@Autowired
	private RedisTemplate<String,String>  redisTemplate;

    private String PREFIX = "/packback/distinguish/";
	@Autowired
	Mq4NotifyDemo mq4NotifyDemo;
    @RequestMapping("")
    public String index(){
        return PREFIX+"distinguishList.html";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object list(String phone,String startTime,String endTime,String status){
    	Page<DistinguishIdCard> page = new PageFactory<DistinguishIdCard>().defaultPage();
		List<DistinguishIdCard> configList=distinguishService.list(page,phone,startTime,endTime,status);
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("rows", configList);
		result.put("total", page.getTotal());
		return result;
    	
    }
    
    /**
     * 撤销审核
     * @param user_id
     * @param status
     * @param error_info
     * @return
     */
    @RequestMapping("/cancel")
    @ResponseBody
    public Object cancel(String user_id)
    {
      	if(StringUtils.isEmpty(user_id))
    	{
    		return super.FailuerTip("用户ID不能为空");
    	}
      	distinguishService.cancel(user_id);
    	return super.SUCCESS_TIP;
    }
    
    
    
    
    /**
     * 审核或者驳回
     * @param user_id
     * @param status
     * @param error_info
     * @return
     */
    @RequestMapping("/changeStatus")
    @ResponseBody
    public Object changeStatus(String user_id,String status,String error_info)
    {
    	ShiroUser shiroUser = ShiroKit.getUser();
    	String userName=shiroUser.getAccount();
    	if(StringUtils.isEmpty(user_id))
    	{
    		return super.FailuerTip("用户ID不能为空");
    	}
    	if(StringUtils.isEmpty(status))
    	{
    		return super.FailuerTip("状态不能为空");
    	}
    	if(status.equals("3"))
    	{
    		if(StringUtils.isEmpty(error_info))
    		{
    			return super.FailuerTip("错误信息不能为空");
    		}
    	}else if(status.equals("1"))   //通过判断有没有在操作出账服务
    	{
    		boolean result= redisTemplate.hasKey("redis_bill_lock");
    		if(result)
    		{
    			String redis_bill_lock=redisTemplate.opsForValue().get("redis_bill_lock");
    			if(redis_bill_lock.equals("open"))
    			{
    				return super.FailuerTip("出账中...请稍后再审核!");
    			}
    		}
    		
    	}
    	redisTemplate.opsForValue().set("redis_bill_lock", "open");
    	try{
    	distinguishService.changeStatus(user_id,status,error_info,userName);

		//模拟手动触发到账, 测试通过
		if("1".equals(status)) {
//			ZoneUserAward award = new ZoneUserAward();
//			award.setUserId(user_id);
//			award = zoneUserAwardMapper.selectOne(award);
//			if (award != null) {
//				Map<String, String> map = new HashMap<String, String>();
//				map.put("unfreeze", "manual");
//				map.put("userId", user_id);
//				map.put("mchOrderNo", "WXSQZC" + user_id);
//				map.put("amount", award.getUserIdAward().toString());
//				map.put("isFree", "isFree");
//				mq4NotifyDemo.send("queue.notify.mch.unfreeze", map.toString());
//
//				map = new HashMap<String, String>();
//				map.put("unfreeze", "manual");
//				map.put("userId", award.getRecommender());
//				map.put("mchOrderNo", "WXSQZC" + user_id);
//				map.put("amount", award.getRecommenderAward().toString());
//				map.put("isFree", "isFree");
//				mq4NotifyDemo.send("queue.notify.mch.unfreeze", map.toString());
//
//				map = new HashMap<String, String>();
//				map.put("unfreeze", "manual");
//				map.put("userId", award.getCommunityAdmin());
//				map.put("mchOrderNo", "WXSQZC" + user_id);
//				map.put("amount", award.getCommunityAdminAward().toString());
//				map.put("isFree", "isFree");
//				mq4NotifyDemo.send(QUEUE_UNFREEZE, map.toString());
//				System.out.println("激活社区注册奖励:" + award.getCommunityAdminAward().toString());
//			}
			ZoneUserAwardThree award = new ZoneUserAwardThree();
			award.setUserId(user_id);
			award = zoneUserAwardThreeMapper.selectOne(award);
			if (award != null) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("unfreeze", "manual");
				map.put("userId", user_id);
				map.put("mchOrderNo", award.getOrderid());
				map.put("amount", award.getUserIdAward().toString());
				map.put("isFree", "isFree");
				mq4NotifyDemo.send("queue.notify.mch.unfreeze", map.toString());

				if(StringUtils.isNotBlank(award.getRecommender())) {
					map = new HashMap<String, String>();
					map.put("unfreeze", "manual");
					map.put("userId", award.getRecommender());
					map.put("mchOrderNo", award.getOrderid());
					map.put("amount", award.getRecommenderAward().toString());
					map.put("isFree", "isFree");
					mq4NotifyDemo.send("queue.notify.mch.unfreeze", map.toString());
				}

				if(StringUtils.isNotBlank(award.getCommunityAdmin())) {
					map = new HashMap<String, String>();
					map.put("unfreeze", "manual");
					map.put("userId", award.getCommunityAdmin());
					map.put("mchOrderNo", award.getOrderid());
					map.put("amount", award.getCommunityAdminAward().toString());
					map.put("isFree", "isFree");
					mq4NotifyDemo.send(QUEUE_UNFREEZE, map.toString());
				}
				System.out.println("激活社区注册奖励:" + award.getCommunityAdminAward().toString());
			}else {
				ZoneUserAward awardCommunity = new ZoneUserAward();
				awardCommunity.setUserId(user_id);
				awardCommunity = zoneUserAwardMapper.selectOne(awardCommunity);
				if (awardCommunity != null) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("unfreeze", "manual");
					map.put("userId", user_id);
					map.put("mchOrderNo", awardCommunity.getOrderid());
					map.put("amount", awardCommunity.getUserIdAward().toString());
					map.put("isFree", "isFree");
					mq4NotifyDemo.send("queue.notify.mch.unfreeze", map.toString());

					if (StringUtils.isNotBlank(awardCommunity.getRecommender())) {
						map = new HashMap<String, String>();
						map.put("unfreeze", "manual");
						map.put("userId", awardCommunity.getRecommender());
						map.put("mchOrderNo", awardCommunity.getOrderid());
						map.put("amount", awardCommunity.getRecommenderAward().toString());
						map.put("isFree", "isFree");
						mq4NotifyDemo.send("queue.notify.mch.unfreeze", map.toString());
					}

					if (StringUtils.isNotBlank(awardCommunity.getCommunityAdmin())) {
						map = new HashMap<String, String>();
						map.put("unfreeze", "manual");
						map.put("userId", awardCommunity.getCommunityAdmin());
						map.put("mchOrderNo", awardCommunity.getOrderid());
						map.put("amount", awardCommunity.getCommunityAdminAward().toString());
						map.put("isFree", "isFree");
						mq4NotifyDemo.send(QUEUE_UNFREEZE, map.toString());
					}
					System.out.println("激活社区注册奖励:" + awardCommunity.getCommunityAdminAward().toString());
				}
			}
		}
    	}catch(Exception ex)
    	{
    		ex.printStackTrace();
    		throw ex;
    	}finally
    	{
    		redisTemplate.opsForValue().set("redis_bill_lock", "close");
    	}
	
    	return super.SUCCESS_TIP;
    }
	
}